def pod_template() {

    yaml = """
    apiVersion: v1
    kind: Pod
    spec:
      serviceAccountName: jenkins
      containers:
        - name: cdk
          image: >-
            396015846097.dkr.ecr.cn-north-1.amazonaws.com.cn/cdk-jenkins-agent:latest
          env:
            - name: APP_ACCOUNT_ROLE
              value: 'arn:aws-cn:iam::397427511450:role/dev-proserve-role'
            - name: DOCKER_HOST
              value: 'tcp://localhost:2375'
            - name: AWS_REGION
              value: 'cn-north-1'
            - name: CDK_DEFAULT_ACCOUNT
              value: '397427511450'
            - name: CDK_DEFAULT_REGION
              value: 'cn-north-1'
            - name: AWS_DEFAULT_REGION
              value: 'cn-north-1'
            - name: CODEBUILD_INITIATOR
              value: 'jenkins'
          command: ["/bin/sh","-c"]
          args: ["cat; npm config set registry https://registry.npm.taobao.org"]
          tty: true
        - name: dind-daemon
          image: 'docker:18.05-dind'
          resources:
            requests:
              cpu: 20m
              memory: 512Mi
          securityContext:
            privileged: true
          volumeMounts:
            - name: docker-graph-storage
              mountPath: /var/lib/docker
      volumes:
        - name: docker-graph-storage
          emptyDir: {}
    """

    return yaml

}

// Switch role
def assum_role(String Role) {
    env.AWS_DEFAULT_REGION = 'cn-north-1'
    sh('aws sts assume-role-with-web-identity --role-arn $' + Role + ' --role-session-name x-account --web-identity-token file://$AWS_WEB_IDENTITY_TOKEN_FILE --duration 7200 > ./temp_creds.json')
    def credential = readJSON file: "./temp_creds.json"
    env.AWS_ACCESS_KEY_ID = credential.Credentials["AccessKeyId"]
    env.AWS_SECRET_ACCESS_KEY = credential.Credentials["SecretAccessKey"]
    env.AWS_SESSION_TOKEN = credential.Credentials["SessionToken"]
    env.TARGET_REGION = 'cn-north-1'
}

def setup_env_for_octagon() {
    env.AWS_REGION = 'cn-north-1'
    env.AWS_PROFILE = 'default'
    env.AWS_CLI_BIN = 'aws'
    env.OCTAGON_INSTANCE = 'dev'
    env.TARGET_REGION = 'cn-north-1'
    env.STAGE = 'dev'
}

def download_mvn_libs() {
    sh('aws s3 sync s3://magna-elec-adas-cicd-deployment/libs $HOME/.m2/repository/com/amazonaws/proserve')
    sh('aws s3 sync s3://magna-elec-adas-cicd-deployment/libs/octagon $HOME/.m2/repository/com/amazonaws/octagon')
}

def download_npm_modules() {
    sh('aws s3 sync s3://magna-elec-adas-cicd-deployment/node_modules  cdk/tmp/node_modules')
    sh('scp -r cdk/tmp/node_modules ${HOME}/node_modules')
}

def build_docker(docker_name, git_full_version) {
    image_version = git_full_version.substring(0, 8)
    ecr_address = '396015846097.dkr.ecr.cn-north-1.amazonaws.com.cn'
    image_latest = ecr_address + '''/''' + docker_name + ''':latest'''
    image = ecr_address + '''/''' + docker_name + ''':''' + image_version
    sh('aws ecr get-login-password --region cn-north-1 | docker login --username AWS --password-stdin ' + ecr_address)
    sh('docker build -t ' + image + ''' .''')
    sh('docker push ' + image)
    sh('docker tag ' + image + ' ' + image_latest)
    sh('docker push ' + image_latest)
}

def deploy_cdk() {
    sh('npm config set registry https://registry.npm.taobao.org')
    sh('npm install -g aws-cdk')
    sh('npm install')
    sh('npm run build')
    sh('cdk deploy --require-approval never')
}

def pipeline_notification(status, error = "") {
    String jobName = env.JOB_NAME
    String repoName = jobName.split('/')[-2]
    String buildNum = env.BUILD_NUMBER
    String commit_id = env.GIT_COMMIT

    Date date = new Date()
    String datePart = date.format("dd/MM/yyyy")
    String timePart = date.format("HH:mm:ss")
    String time = datePart + ' ' + timePart

    // If failed, send the detailed logs
    if (status == 'FAILED') {
        output = readFile('commandResult').trim()
        error = error + output
        sh(script: "cat commandResult", label: "This is the output logs")
    }

    String messageBase = "Job $repoName $status at $time UTC \n Build number is: $buildNum \n Commit ID is: $commit_id \n Build URL is: $env.BUILD_URL \n"
    String message = status == 'FAILED' ? messageBase + "Error logs: $error" : messageBase
    String topicName = "$repoName-cn-region-branch-cicd-topic"
    String topicArn = "arn:aws:sns:eu-central-1:549162098672:$topicName"

    env.topicArn = topicArn
    env.message = message
    env.topicName = topicName

    create_sns_if_not_exist()

    def snsPub = libraryResource 'snsPub.sh'
    writeFile file: 'snsPub.sh', text: snsPub
    sh 'sh snsPub.sh'
}

// check whether the sns topic exist or not
def create_sns_if_not_exist() {
    def createSns = libraryResource 'createSns.sh'
    writeFile file: 'createSns.sh', text: createSns
    sh 'sh createSns.sh'
}


def deploy_script() {
    // set env for deploy
    env.COMMIT_ID = env.GIT_COMMIT

    sh 'bash scripts/deploy.sh &> commandResult'
    output = readFile('commandResult').trim()
    sh(script: "cat commandResult", label: "This is the output logs for deploy")
}

def build_and_push_image() {
    sh 'bash build_and_push_image.sh &> commandResult'
    output = readFile('commandResult').trim()
    sh(script: "cat commandResult", label: "This is the output logs for build and push image")
}

def build_script() {
    rebuild_netfailed()
}

// rebuild with "sh build.sh" three times if it is network failed reason
def rebuild_netfailed() {
    boolean flag = true
    Integer num = 0
    while (flag) {
        try {
            build_script_core()
            flag = false
        } catch (Exception e) {
            flag = check_network(num++)
        }
    }
}

// check whether it is a network problem
def check_network(num) {
    if (num > 2) {
        utilities.pipeline_notification('FAILED', e.toString())
        error('Stopping early…')
    }
    num++
    output = readFile('commandResult').trim()
    // if the error log has these message, it means there is a network problem.
    boolean flag = (output.contains("error pulling image configuration") && output.contains("TLS handshake timeout"))
    return flag
}

def build_script_core() {
    // set env for build
    env.COMMIT_ID = env.GIT_COMMIT

    sh 'bash scripts/build.sh &> commandResult'
    output = readFile('commandResult').trim()
    sh(script: "cat commandResult", label: "This is the output logs for build")
}

def build_java_image(version,deployRemote) {
    sh "cp webapp/target/*.jar k8sconfig/dockerfile && rm -fr k8sconfig/dockerfile/*-javadoc.jar && rm -fr k8sconfig/dockerfile/*-sources.jar"
    dir ('./k8sconfig') {
        sh "export VERSION=$version && skaffold build -f skaffold.yaml"
    }
    if(BRANCH_NAME.startsWith('master')){
        dir ("./k8sconfig/charts/${projectArtifactId}") {
            //FIXME 命令空间目前固定为TEST
            sh "export FILE_NAME=$projectArtifactId && export NAMESPACE=test && export RELEASE_VERSION_3=$version && make tag3"
            sh "export FILE_NAME=$projectArtifactId && export ALIYUN=$deployRemote && make release"
        }
    }
    if(deployRemote){
        sh "export VERSION=`cat VERSION` && docker tag $DOCKER_REGISTRY/$ORG/$projectArtifactId:$version $DOCKER_REGISTRY_ALIYUN/kms/$projectArtifactId:$version"
        sh "export VERSION=`cat VERSION` && docker push $DOCKER_REGISTRY_ALIYUN/kms/$projectArtifactId:$version"
        sh "docker rmi -f $DOCKER_REGISTRY_ALIYUN/kms/$projectArtifactId:$version"
    }
    sh "docker rmi -f $DOCKER_REGISTRY/$ORG/$projectArtifactId:$version"

}

//def deploy_app(spaces,projectArtifactId){
//    sh "helm template -n $spaces --output-dir $WORKSPACE/k8sconfig . "
//    sh "kubectl apply -f $WORKSPACE/k8sconfig/$projectArtifactId/templates/ -n $spaces "
//    //删除容器重新加载新部署的镜像
//    sh "kubectl get pod -n $spaces  |grep $projectArtifactId | awk '{print \$1}'|xargs -I {} kubectl delete pod -n $spaces  {} --force --grace-period=0"
//    sh "chown -R 10000:10000 ../$spaces"
//}
